package com.whfc.iot.fse.crane.codec;

import com.whfc.iot.fse.crane.entity.TwConst;
import com.whfc.iot.fse.crane.entity.TwMsg;
import com.whfc.iot.fse.crane.util.TwMsgUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 塔吊消息编码器
 */
public class TwMsgEncoder extends MessageToMessageEncoder<TwMsg> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, TwMsg msg, List<Object> out) throws Exception {

        String dustMsg = TwMsgUtil.encode(msg);
        ByteBuf buf = Unpooled.buffer(dustMsg.length());
        buf.writeCharSequence(dustMsg, TwConst.UTF8);
        logger.info("发送消息,{}", dustMsg);
        logger.info(ByteBufUtil.prettyHexDump(buf));
        out.add(buf);
    }
}
